package libaryinterface.user;

import libaryinterface.interfaceutils.MyDialogDemo;
import libaryinterface.interfaceutils.OuttimeInterface;
import pojo.vo.BookRecordVo;
import service.BookRecordService;
import service.impl.BookRecordServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-12-07
 * Time: 20:04
 */
//用户归还界面
public class UserReturnInterface extends JFrame {
    int i =0;
    public UserReturnInterface(String account) throws SQLException {
        //设置窗口
        super("用户归还界面");
        //1.把图片添加到标签里（把标签的大小设为和图片大小相同），把标签放在分层面板的最底层；
        ImageIcon bg = new ImageIcon("src//picture//excel.jpg");
        JLabel label1 = new JLabel(bg);
        label1.setSize(bg.getIconWidth(),bg.getIconHeight());
        UserReturnInterface.super.getLayeredPane().add(label1,new Integer(Integer.MIN_VALUE));
        //2.把窗口面板设为内容面板并设为透明、流动布局。
        JPanel p1=(JPanel)UserReturnInterface.super.getContentPane();
        p1.setOpaque(false);
        p1.setLayout((new FlowLayout()));


        Container container = this.getContentPane();
        setBounds(500,400,1000,1200);
        // 表头（列名）
        Object[][] rowData = new Object[100][11];
        BookRecordService bookRecordService = new BookRecordServiceImpl();
        //记录当前的条数
        List<BookRecordVo> bookRecordVoList = bookRecordService.listBookRecordByAccount(account);
        String[] columnNames = {"编号","书名","借阅人", " 借阅时间 ", "规定归还时间","实际归还时间", "是否逾期","借阅天数","借阅数量","罚款金额","是否归还"};
        for (BookRecordVo record: bookRecordVoList) {
            //获取信息
            Long snid =  record.getId();
            String name = record.getName();
            String author = record.getNickName();
            LocalDate lendTime = record.getLendTime();
            LocalDate returnTime = record.getReturnTime();
            LocalDate realTime = record.getRealTime();
            String isOverdue = record.getIsOverdue();
            Long loanLength = record.getLoanLength();
            Long loanNumber = record.getLoanNumber();
            double fineMoney = record.getFineMoney();
            String state = record.getState();
            //放入表格数组中
            rowData[i][0] = snid;
            rowData[i][1] = name;
            rowData[i][2] = author;
            rowData[i][3] = lendTime;
            rowData[i][4] = returnTime;
            rowData[i][5] = realTime;
            rowData[i][6] = isOverdue;
            rowData[i][7] = loanLength;
            rowData[i][8] = loanNumber;
            rowData[i][9] = fineMoney;
            rowData[i][10] = state;
            i++;
        }

        //设置标签
        JLabel label = new JLabel("总数量: " + bookRecordVoList.size());
        label.setBounds(100,20,150,40);
        label.setFont(new Font(null, Font.PLAIN, 20));
        label.setForeground(Color.GREEN);


        // 创建一个表格，指定 表头 和 所有行数据
        JTable table = new JTable(rowData, columnNames);

        // 设置表格内容颜色
        table.setForeground(Color.BLACK);                   // 字体颜色
        table.setFont(new Font(null, Font.CENTER_BASELINE,15));      // 字体样式
        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
        table.setSelectionBackground(Color.YELLOW);     // 选中后字体背景
        table.setGridColor(Color.GRAY);                     // 网格颜色
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();//单元格渲染器
        tcr.setHorizontalAlignment(JLabel.CENTER);//居中显示
        table.setDefaultRenderer(Object.class, tcr);//设置渲染器
        // 设置表头
        table.getTableHeader().setFont(new Font(null, Font.BOLD, 15));  // 设置表头名称字体样式
        table.getTableHeader().setForeground(Color.RED);                // 设置表头名称字体颜色
        table.getTableHeader().setResizingAllowed(true);               // 设置不允许手动改变列宽
        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高
        table.setRowHeight(40);

        // 第一列列宽设置为40
        table.getColumnModel().getColumn(0).setPreferredWidth(40);

        // 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
        table.setPreferredScrollableViewportSize(new Dimension(400, 300));
        // 把 表格 放到 滚动面板 中（表头将自动添加到滚动面板顶部）
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(150,150,1200,600);

        //归还按钮
        JButton button = new JButton("归还");
        button.setBounds(650,910,100,30);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取当前的行列数
                int index = 0;
                try {
                    index = table.getSelectedRow();
                    //判断选中行是否有信息
                    if( index >= i) {new MyDialogDemo("请选中有信息的行!"); return;}

                    Long recordId = (Long) rowData[index][0];//获取选中记录的id
                    String bookName = (String) rowData[index][1];//获取选中记录的书名
                    Long reutrnNumber = (Long) rowData[index][8];//获取选中记录的借阅数量
                    String over = (String) rowData[index][6];
                    String state = (String) rowData[index][10];
                    if(state.equals("是") ){
                        new MyDialogDemo("该书已归还!");
                        return ;
                    }
                    if(over.equals("是")) {
                        OuttimeInterface outtimeInterface = new OuttimeInterface(recordId, bookName, reutrnNumber, account);
                        if(outtimeInterface!=null){
                            UserReturnInterface.super.dispose();
                            new UserReturnInterface(account);
                        }
                    } else {
                        //进行还书操作
                        boolean flag = bookRecordService.returnRecord(recordId, bookName, reutrnNumber, account);
                        if(flag ){
                            //归还成功后自动刷新页面
                            UserReturnInterface.super.dispose();
                            new UserReturnInterface(account);
                            new MyDialogDemo("归还成功");
                        }
                    }
                } catch (Exception ex) {
                    new MyDialogDemo("未选中行!");
                }
            }
        });
        container.add(label);
        container.add(button);
        // 添加 滚动面板 到 内容面板
        container.add(scrollPane);
        //获得容器
        container.setBackground(new Color(50, 144, 236));
        container.setLayout(null);
        //container.setVisible(true);
        setBounds(180,1,1500,1200);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);


    }
}
